package com.ruoyi.gbase.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.gbase.domain.GbaseJobInfo;
import com.ruoyi.gbase.domain.GbaseLoadCount;
import com.ruoyi.gbase.domain.TableInfo;
import com.ruoyi.gbase.domain.VSms;
import com.ruoyi.gbase.service.IGbaseJobInfoService;
import com.ruoyi.gbase.service.ITableInfoService;
import com.ruoyi.gbase.service.IVSmsService;
import com.ruoyi.gbase.util.GbaseLoadUtil;
import com.ruoyi.gbase.util.GbaseUtil;
import com.ruoyi.gbase.util.SMSUtil;
import com.ruoyi.nsh.util.DateUtil;
import com.ruoyi.quartz.domain.SysJob;
import com.ruoyi.quartz.service.ISysJobService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * 下发基础表Controller
 * 
 * @author yys
 * @date 2020-10-27
 */
@RestController
@RequestMapping("/test")
public class TtestController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(TtestController.class);
    private String prefix = "gbase/test";

    @Autowired
    private GbaseUtil gbaseUtil;

    @Autowired
    private ITableInfoService tableInfoService;
    @Autowired
    private GbaseLoadUtil gbaseLoadUtil;
    @Autowired
    private IGbaseJobInfoService gbaseJobInfoService;

    @Autowired
    private IVSmsService vSmsService;
    @Autowired
    private ISysJobService jobService;

    /**
     * 测试调用存储过程
     */
    @GetMapping("/c")
    public String call() throws SQLException, ClassNotFoundException {
        gbaseUtil.connectGBase();
        gbaseUtil.callPro("call jx.test_exception(@code,@o2,@msg);");
        return prefix + "/result";
    }

   
    /**
     * 测试直接发送短信列表的数据
     */
    @GetMapping("/sendSms")
    public String sendSms() throws SQLException, ClassNotFoundException {
        List<VSms> vSmsList = vSmsService.selectVSmsList(null);
        for(VSms v:vSmsList){
            if(v.getIssend()==0){
                log.info("更新已发送记录:"+v.getId());
                vSmsService.updateVSms(v);
                log.info("发动短信："+v.getTelphone()+" content："+v.getContent()+" id:"+v.getId());
                SMSUtil.sendSms(v.getTelphone(),v.getContent());

                //这里是手动测试，直接再发个给自己
                //log.info("发动短信给yin测试：13852532209 content："+v.getContent()+" id:"+v.getId());
                //SMSUtil.sendSms("13852532209",v.getContent());
            }
        }

        return prefix + "/result";
    }
    /**
     * 将最近一天的所有的表的gbase数据给更新一下
     */
    @GetMapping("/setgCount")
    public String setgCount() throws SQLException, ClassNotFoundException {
        gbaseUtil.connectGBase();

        GbaseJobInfo gbaseJobInfo = new GbaseJobInfo();
        gbaseJobInfo.setEtlDate(DateUtil.addDay(DateUtils.getdateYYYYMMDD(), -1));
        List<GbaseJobInfo> glist = gbaseJobInfoService.selectGbaseJobInfoList(gbaseJobInfo);
        int i =0;
        for(GbaseJobInfo g:glist){
            //一条条做
            String inccount = "select count(*) num from " + g.getSchemaName() + "." + g.getTableName() + ";";
            ResultSet ri = gbaseUtil.query(inccount);
            if (ri.next()) {
                i = ri.getInt(1);
                g.setInccount(ri.getInt(1));
                log.info("更新：" + g.getSchemaName() + "." +  g.getTableName() +" 数据量:"+i);
                gbaseJobInfoService.updateGbaseJobInfo(g);
            }
        }

        return prefix + "/result";
    }

    /**
     * 单独直接刷  im.dim_alltables 里面的数据
     */
    @ResponseBody
    @GetMapping(value = {"/singleUpdate/{schemaName}/{tableName}", "/singleUpdate/{schemaName}", "/singleUpdate"})
    public void singleUpdate(@PathVariable(value = "schemaName", required = false) String schemaName,
                             @PathVariable(value = "tableName", required = false) String tableName) {
        log.info("singleUpdate开始单个处理表：" + schemaName + "." + tableName);
        TableInfo query = new TableInfo();
        query.setEtlDate(DateUtil.addDay(DateUtils.getdateYYYYMMDD(), -1));
        query.setSchemaName(schemaName.toUpperCase());
        query.setTableName(tableName.toUpperCase());
        //根据昨天的日期查询所有的下发表
        List<TableInfo> tableInfoList = tableInfoService.selectTableInfoList(query);
        log.info("开始singleUpdate 表数量：" + tableInfoList.size());
        for (TableInfo t : tableInfoList) {
            gbaseLoadUtil.updateALLTABLES(t);
        }

        log.info("就算没有入库，也直接强行更新一下自己的表：" + tableName);
        String updateSQL = "update IM.DIM_ALLTABLES set sjcount=(SELECT COUNT(*) num FROM "+schemaName+"."+tableName+")  where UPPER(TABLE_SCHEMA)='"+schemaName.toUpperCase()+"' and UPPER(TABLE_NAME)='"+tableName.toUpperCase()+"' ";

        log.info("updateSQL：" + updateSQL);
        try {
            gbaseUtil.connectGBase();
            gbaseUtil.update(updateSQL,null);
        } catch (Exception e) {
            log.info(schemaName+"."+tableName+"出现了异常，跳出重新处理"+e.toString());
            return ;
        }
        return;
    }

    /**
     * 单独直接刷  im.dim_alltables 里面的数据
     */
    @ResponseBody
    @GetMapping(value = {"/setDB2COUNT/{schemaName}/{tableName}", "/singleUpdate/{schemaName}", "/singleUpdate"})
    public void setDB2COUNT(@PathVariable(value = "schemaName", required = false) String schemaName,
                            @PathVariable(value = "tableName", required = false) String tableName) {
        log.info("setDB2COUNT开始单个处理表：" + schemaName + "." + tableName);
        TableInfo query = new TableInfo();
        query.setEtlDate(DateUtil.addDay(DateUtils.getdateYYYYMMDD(), -1));
        query.setSchemaName(schemaName.toUpperCase());
        query.setTableName(tableName.toUpperCase());
        //根据昨天的日期查询所有的下发表
        List<TableInfo> tableInfoList = tableInfoService.selectTableInfoList(query);
        for (TableInfo t : tableInfoList) {
            String schema2 = t.getSchemaName();
            String tablename2 = t.getTableName();
            log.info("开始更新DB2数量表：" + schema2 + "." + tablename2 + " 查询数据库中……");

            //查询到DB2表的数据量
            int db2count = tableInfoService.selectCount(t);
            log.info("表：" + schema2 + "." + tablename2 + "  获取到db2表数据：" + db2count);
            String updateSQL = "update IM.DIM_ALLTABLES set DB2COUNTetl_dt='" + DateUtils.getdateYYYYMMDD() + "',db2count=" + db2count + " where UPPER(TABLE_SCHEMA)='" + schema2 + "' and UPPER(TABLE_NAME)='" + tablename2 + "' ";
            try {
                gbaseUtil.connectGBase();
                gbaseUtil.update(updateSQL, null);
            } catch (Exception e) {
                log.info(schema2 + "." + tablename2 + "出现了异常，跳出重新处理" + e.toString());

                return ;
            }

        }

        return ;

    }

    /**
     * 给13852532209 自己发短信
     */
    @ResponseBody
    @GetMapping(value = "/sendToyin/{content}")
    public void sendToyin(@PathVariable(value = "content", required = false) String content) {
        String rq = DateUtil.addDay(DateUtils.getdateYYYYMMDD(),-1);
        GbaseLoadCount gbaseJobInfo = gbaseJobInfoService.selectGbaseLoadCount(rq);
        int xfnum = 0;
        int rknum = 0;

        AjaxResult ajax = AjaxResult.success();
        ajax.put("rq", rq);
        if(gbaseJobInfo!=null){
            xfnum = gbaseJobInfo.getDbnums();
            rknum = gbaseJobInfo.getGbasenums();
        }

        //存储过程结果
        SysJob job = new SysJob();
        job.setJobGroup("PROC");
        List<SysJob> list = jobService.selectJobList(job);
        job.setExecDt(DateUtil.addDay(DateUtils.getdateYYYYMMDD(),-0));
        job.setExecStatus("执行成功");
        List<SysJob> list2 = jobService.selectJobList(job);
        job.setExecDt(null);
        job.setExecStatus("执行失败");
        List<SysJob> listfail = jobService.selectJobList(job);
        job.setExecDt(null);
        job.setExecStatus("正在执行");
        List<SysJob> listing = jobService.selectJobList(job);

        SMSUtil.sendSms("13852532209",rq+"下发:" + xfnum + " 已入库:"
                + rknum+" 存储过程："+list.size()+" 成功："+list2.size()
            +" 失败："+listfail.size()+" 正在执行：" +listing.size());
        return;
    }


}